package com.tlgen.controller;

import com.alibaba.fastjson.JSONObject;
import com.tlgen.Model.ConfigData;
import com.tlgen.comon.R;
import com.tlgen.factory.ConfigLocalFactory;
import com.tlgen.service.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

/*
 *@title DistroController
 *@description
 *@author ta151486
 *@version 1.0
 *@create 2023/12/12 18:23
 */
@RestController
@RequestMapping("/config")
public class ConfigController {

    @Autowired
    private ConfigService configService;

    @PostMapping("/receive")
    public R receive(@RequestBody ConfigData configData, HttpServletRequest request) {
        String serverPort = request.getRemoteHost() + ":" + request.getServerPort();
        System.out.println("已同步来自 " + serverPort + " 的数据: " + JSONObject.toJSONString(configData));
        configService.saveToLocalInstance(configData);
        return R.ok("SUCCESS");
    }

    @GetMapping("/update")
    public R test() {
        ConfigData configData = new ConfigData();
        configData.setVersion(LocalDateTime.now()
                .toInstant(ZoneOffset.ofHours(8))
                .toEpochMilli());
        configData.setContent("1234");
        ConfigLocalFactory.getInstance().setConfigData(configData);

        configService.updateToLocalInstance(configData);

        return R.ok("SUCCESS");
    }

    @GetMapping("/select")
    public R select() {
        System.out.println(ConfigLocalFactory.getInstance().getConfigData());
        return R.ok(ConfigLocalFactory.getInstance().getConfigData(), "SUCCESS");
    }

}
